package com.legsem.legstar.cci;

import javax.naming.NamingException;
import javax.naming.Reference;
import javax.resource.ResourceException;
import javax.resource.cci.Connection;
import javax.resource.cci.ConnectionFactory;
import javax.resource.cci.ConnectionSpec;
import javax.resource.cci.RecordFactory;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ManagedConnectionFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * ConnectionFactory provides an interface for getting connection to an EIS
 * instance. An implementation of ConnectionFactory interface is provided by a
 * resource adapter. Application code looks up a ConnectionFactory instance from
 * JNDI namespace and uses it to get EIS connections. An implementation class
 * for ConnectionFactory is required to implement java.io.Serializable and
 * javax.resource.Referenceable interfaces to support JNDI registration.
 * 
 */
public abstract class LegStarConnectionFactoryImpl implements
        ConnectionFactory {

    private static final long serialVersionUID = -2896852165121774642L;

    /** Logger. */
    private final Log log = LogFactory.getLog(getClass());

    private static final String RECORD_FACTORY_ERROR = "The LegStar interactions do not use records. Use standard JAXB objects instead.";

    private ManagedConnectionFactory managedConnectionFactory;
    private ConnectionManager connectionManager;
    private Reference reference;

    public LegStarConnectionFactoryImpl(ManagedConnectionFactory mcf,
            ConnectionManager cm) {

        super();
        this.managedConnectionFactory = mcf;
        this.connectionManager = cm;
    }

    public Connection getConnection() throws ResourceException {
        if (log.isDebugEnabled()) {
            log.debug("Getting connection");
        }
        return (Connection) connectionManager.allocateConnection(
                managedConnectionFactory, null);
    }

    public Connection getConnection(ConnectionSpec connectionSpec)
            throws ResourceException {
        if (log.isDebugEnabled()) {
            log.debug("Getting connection with specs: " + connectionSpec);
        }
        return (Connection) connectionManager.allocateConnection(
                managedConnectionFactory, new LegStarConnectionRequestInfo(
                        (LegStarConnectionSpec) connectionSpec));
    }

    public void setReference(Reference reference) {
        this.reference = reference;

    }

    public Reference getReference() throws NamingException {
        return reference;
    }

    public RecordFactory getRecordFactory() throws ResourceException {
        throw new ResourceException(RECORD_FACTORY_ERROR);
    }

    public ConnectionManager getConnectionManager() {
        return connectionManager;
    }

}
